import axios, { AxiosError, type AxiosRequestHeaders, type AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import downLoad from './downLoad'
import { sse } from './sse'
import JMessage from './JMessage'

/* 定义response对象的data接口 */
interface ResponseData<T> {
  code: number
  data: T
  message: string
}

// 配置新建一个 axios 实例
const SynchronizationLoginWork = axios.create({
  baseURL: '/kl',
  timeout: 500000
})

const token = sessionStorage.getItem('Authorization')

// 添加请求拦截器
SynchronizationLoginWork.interceptors.request.use(
  (config: any) => {
    const token = sessionStorage.getItem('Authorization')
    const lang = localStorage.getItem('language')
    if (token) {
      ;(config.headers as AxiosRequestHeaders).Authorization = token
    }
    if (lang && lang !== 'undefined') {
      ;(config.headers as AxiosRequestHeaders)['Accept-Language'] = lang
    }
    config.headers['X-Mirror-Enable'] = 'true'

    return config
  },
  (error) => {
    // 处理请求错误
    return Promise.reject(error)
  }
)

// 添加响应拦截器
SynchronizationLoginWork.interceptors.response.use((response: any) => {
  let res = response.data

  if (res.code === 200) {
    return res
  }
  if (res.code === 210) {
    JMessage.warning(res.message)
    sse()
  }

  if (res.code === 3) {
    JMessage.warning('登录超时请重新登录')
    sessionStorage.removeItem('Authorization')
    setTimeout(() => {
      window.location.href = '/'
    }, 1000)
  } else {
    return res
  }
})

export default SynchronizationLoginWork
